package com.zhixing.myboot.framework.configurer;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Arrays;

@Configuration
@EnableCaching
public class CacheConfigurer extends CachingConfigurerSupport {

    /**
     * 缓存默认过期时间，单位：秒
     */
    public static final long DEFAULT_EXPIRATION = 3600 * 12;

    @Resource
    private RedisTemplate redisTemplate;

    @Bean
    public CacheManager cacheManager() {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        rcm.setCacheNames(Arrays.asList("cache"));
        rcm.setDefaultExpiration(DEFAULT_EXPIRATION);
        return rcm;
    }

    @Bean
    public CacheResolver cacheResolver() {
        return new SimpleCacheResolver(cacheManager());
    }

    /*@Bean
    public KeyGenerator keyGenerator() {
        return (o, method, objects) -> {
            String cachePrefix = o.getClass().getSimpleName().replace("ServiceImpl", "");
            String cacheId = StringUtils.EMPTY;
            String methodName = method.getName();
            if (methodName.equals("findById")) {
                cacheId = String.valueOf(objects[0]);
            } else if (methodName.equals("update")){

            }

            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName());
            sb.append(method.getName());
            for (Object obj : objects) {
                sb.append(obj.toString());
            }
            System.err.println("--------------------------------------keyGenerator=" + sb.toString());
            return sb.toString();
        };
    }*/
}
